package cn.fancy.sdk.crash;

import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import cn.fancy.sdk.entity.GuildBaseInfo;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class QCCrashHandler implements UncaughtExceptionHandler {
    
    public static final String TAG = "QCCrashHandler";
    
    //系统默认的UncaughtException处理类   
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    
    private static QCCrashHandler instance = new QCCrashHandler();
    
    private Context mContext;
    
    private Map<String, String> infos = new HashMap<String, String>();
    
    //用于格式化日期,作为文件内容的一部分  
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    
    private QCCrashHandler() {
    }
    
    public static QCCrashHandler getInstance() {
        return instance;
    }
    
    /**
     * 初始化
     */
    public void init(Context context) {
        mContext = context;
        //获取系统默认的UncaughtException处理器  
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为程序的默认处理器  
        Thread.setDefaultUncaughtExceptionHandler(this);
        //保存设备信息+公用信息
        initDeviceMess(context);
        //初始化输出对象
        QCCrashLogPrint.getInstance().initPrint(context);
    }
    
    
    private void initDeviceMess(Context context) {
        if (infos != null) {
            infos = new HashMap<>();
        }
        GuildBaseInfo.getInstance().addDeviceMess(infos, context);
    }
    
    
    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理  
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            //退出程序  
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }
    
    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //提示异常消息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();
        //生成日志信息并保持到crash文件
        SaveCrashInfo(ex);
        return true;
    }
    
    
    
    private void SaveCrashInfo(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        long timestamp = System.currentTimeMillis();
        String time = formatter.format(new Date());
        sb.append(time + "\n");
        
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }
        
        //获取闪退信息
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        
        sb.append(result);
        
        QCCrashLogPrint.getInstance().printCrash(sb.toString());
    }
    
}  


